/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tree;

import editor.Editor;
import editor.MenuToolBar;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author RoderickNestor
 */
public class TreeProject {

    private Editor editor;
    public JTree tree;
    private JPopupMenu popup;
    private DefaultTreeModel treeModel = null;

    private ImageIcon ico_file = createImageIcon("img/text-x-generic.png");

    public TreeProject(Editor editor) {
        this.editor = editor;
        tree = new JTree(treeModel);
        makeTree();
        makepopup();
    }

    private void makeTree() {

        tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                if (node == null) {
                    return;
                }
                TreeNode selectedNode_parent = null;
                if (node.getParent() != null) {
                    selectedNode_parent = node.getParent();
                }

                File node_file = new File(node.toString());
                if (node_file.exists()) {
                    editor.panelSouth.setStatus(node.toString());
                } else {
                    File selectedNode;
                    if (selectedNode_parent != null) {
                        editor.panelSouth.setStatus("file : " + selectedNode_parent.toString() + File.separator + node.toString());
                        selectedNode = new File(selectedNode_parent.toString() + File.separator + node.toString());
                    } else {
                        editor.panelSouth.setStatus("file : " + File.separator + node.toString());
                        selectedNode = new File(File.separator + node.toString());
                    }

                    String content = "";
                    if (selectedNode.isFile()) {
                        //preview.setText(null);
                        try {
                            BufferedReader br = new BufferedReader(new FileReader(selectedNode));
                            String line = "";
                            while ((line = br.readLine()) != null) {
                                content += line;
                                content += System.getProperty("line.separator");

                            }
                        } catch (Exception exc) {
                            exc.printStackTrace();
                        }
                    }

                    editor.tab.addTab(selectedNode_parent.toString() + File.separator + node.toString());
                }

            }
        });
        tree.setCellRenderer(new DefaultTreeCellRenderer() {
            @Override
            public Component getTreeCellRendererComponent(
                    JTree tree, Object value,
                    boolean sel, boolean expanded,
                    boolean leaf, int row, boolean hasFocus) {

                super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
                File currentFile = new File(value.toString());
                setText(currentFile.getName());
                if (!currentFile.isDirectory()) {
                    setIcon(ico_file);
                }
                return this;
            }
        });
        tree.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent e) {
                int row = tree.getRowForLocation(e.getX(), e.getY());
                if (row == -1) {
                    return;
                }
                tree.setSelectionRow(row);
                if (e.isPopupTrigger()) {
                    popup.show((JComponent) e.getSource(),
                            e.getX(), e.getY());
                }
            }
        }
        );
    }

    public void makepopup() {
        popup = new JPopupMenu();
        JMenuItem newFile = new JMenuItem("New File");
        newFile.setIcon(createImageIcon("img/text-x-generic.png"));
        newFile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTextField txtNameFile = new JTextField();
                Object[] message = {"Name File:", txtNameFile};
                Icon pie = null;
                pie = createImageIcon("img/text-x-generic.png");

                int option = JOptionPane.showConfirmDialog(null, message, "New File", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, pie);
                if (option == JOptionPane.OK_OPTION) {
                    TreePath path = tree.getSelectionPath();
                    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent();
                    int count = parent.getChildCount();
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode(txtNameFile.getText());
                    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                    model.insertNodeInto(child, parent, count);
                    tree.expandPath(path);
                    String path_url = parent.toString() + File.separator + child;
                    try {
                        FileWriter fw = new FileWriter(path_url);
                        fw.write("");
                        fw.close();
                    } catch (IOException ee) {
                        System.out.println("Can't open file '' for writing :: " + path_url);
                        return;
                    }
                }
            }
        });

        JMenuItem newFolder = new JMenuItem("New Folder");
        newFolder.setIcon(createImageIcon("img/folder16.png"));
        newFolder.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTextField txtNameFile = new JTextField();
                Object[] message = {"Name Folder:", txtNameFile};
                Icon pie = null;
                pie = createImageIcon("img/folder16.png");
                int option = JOptionPane.showConfirmDialog(null, message, "New Folder", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, pie);
                if (option == JOptionPane.OK_OPTION) {
                    TreePath path = tree.getSelectionPath();
                    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent();
                    int count = parent.getChildCount();
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode(txtNameFile.getText());
                    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                    model.insertNodeInto(child, parent, count);
                    tree.expandPath(path);
                    String path_url = parent.toString() + File.separator + child;

                    File fw = new File(path_url);
                    fw.mkdir();
                }
            }
        });

        JMenuItem delete = new JMenuItem("Delete");
        delete.setIcon(createImageIcon("img/process-stop.png"));
        delete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int n = JOptionPane.showConfirmDialog(
                        null,
                        "Would you like to delete?",
                        "Delete",
                        JOptionPane.YES_NO_OPTION);
                if (n == JOptionPane.YES_OPTION) {
                    DefaultMutableTreeNode dmtn, node;
                    TreePath path = tree.getSelectionPath();
                    dmtn = (DefaultMutableTreeNode) path.getLastPathComponent();
                    node = (DefaultMutableTreeNode) dmtn.getParent();
                    String str_node = node.toString();
                    int nodeIndex = node.getIndex(dmtn);
                    dmtn.removeAllChildren();
                    node.remove(nodeIndex);
                    ((DefaultTreeModel) tree.getModel()).nodeStructureChanged((TreeNode) dmtn);
                    tree.expandPath(path.getParentPath());
                    File fw = new File(str_node + File.separator + dmtn.toString());
                    if (fw.delete()) {
                        System.out.println(fw.getName() + " is deleted!");
                    } else {
                        System.out.println("Delete operation is failed.");
                    }
                }
            }
        });

        popup.add(newFile);
        popup.add(newFolder);
        popup.addSeparator();
        popup.add(delete);
        popup.setOpaque(true);
        popup.setLightWeightPopupEnabled(true);

    }

    public void setModel(String projectLocation) {
        treeModel = new DefaultTreeModel(addNodes(null, new File(projectLocation)));
        tree.setModel(treeModel);
    }

    public void close() {
        treeModel = null;
        tree.setModel(treeModel);
    }
    
        protected final ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = TreeProject.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
            }
        }
           

    private DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) {
        String curPath = dir.getPath();
        DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath);
        if (curTop != null) {
            curTop.add(curDir);
        }
        Vector<String> ol = new Vector<String>();
        String[] tmp = dir.list();
        for (int i = 0; i < tmp.length; i++) {
            ol.addElement(tmp[i]);
        }
        Collections.sort(ol, String.CASE_INSENSITIVE_ORDER);
        File f;
        Vector<Object> files = new Vector<Object>();
        for (int i = 0; i < ol.size(); i++) {
            String thisObject = ol.elementAt(i);
            String newPath;
            if (curPath.equals(".")) {
                newPath = thisObject;
            } else {
                newPath = curPath + File.separator + thisObject;
            }
            if ((f = new File(newPath)).isDirectory()) {
                if (!f.getName().equals("tmp")) {
                    addNodes(curDir, f);
                }

            } else {
                files.addElement(thisObject);
            }
        }
        for (int fnum = 0; fnum < files.size(); fnum++) {
            curDir.add(new DefaultMutableTreeNode(files.elementAt(fnum)));
        }
        return curDir;
    }

    public void clear() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}
